package com.acenodie.acenodieopenglturorial.Camera1Demo2;

import android.content.Context;
import android.graphics.Point;
import android.graphics.SurfaceTexture;
import android.opengl.GLES20;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import com.acenodie.acenodieopenglturorial.Camera1Demo.CameraDrawer;
import com.acenodie.acenodieopenglturorial.filter.AFilter;
import com.acenodie.acenodieopenglturorial.source.AiyaCamera1;
import com.acenodie.acenodieopenglturorial.source.ICameraSource;

/**
 * Created by zhangb2 on 17.6.6.
 */

public class CameraView2 extends SurfaceView implements SurfaceHolder.Callback{

    private ICameraSource mCamera1;
    private CameraDrawer2 mCameraDrawer2;
    private int cameraId=1;

    private EGLHelper eglHelper;

    private Runnable mRunnable;

    public CameraView2(Context context) {
        this(context,null);
    }

    public CameraView2(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init(){
        getHolder().addCallback(this);
        mCamera1=new AiyaCamera1();
        mCameraDrawer2=new CameraDrawer2(getResources());
    }

    public void switchCamera(){
        mRunnable=new Runnable() {
            @Override
            public void run() {
                mCamera1.close();
                cameraId=cameraId==1?0:1;
            }
        };
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        mCameraDrawer2.surfaceCreated(holder);
        if(mRunnable!=null){
            mRunnable.run();
            mRunnable=null;
        }
        mCamera1.open(cameraId);
        mCameraDrawer2.setCameraId(cameraId);
        Point point=((AiyaCamera1)mCamera1).getPreviewSize();
        mCameraDrawer2.setDataSize(point.x,point.y);
        mCamera1.setPreviewTexture(mCameraDrawer2.getSurfaceTexture());

        eglHelper = new EGLHelper();
        eglHelper.config(8,8,8,8,16,4);
        eglHelper.setSurfaceType(EGLHelper.SURFACE_WINDOW, holder.getSurface());
        eglHelper.eglInit(point.x,point.y);
        GLES20.glClearColor(0, 0, 0, 0);
        GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
        eglHelper.swapBuffers();

        mCamera1.startPreview();
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        mCameraDrawer2.setViewSize(width,height);
        GLES20.glViewport(0,0,width,height);
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {

    }

    public void onResume(){

    }

    public void onPause() {
        mCamera1.close();
    }
}
